# -*- coding: utf-8 -*-
########################################################################
#   Pax-Selector. Copyright 2010, Hector Sanjuán.                      #
#                                                                      #
#   Pax-selector is free software: you can redistribute it and/or      #
#   modify it under the terms of the GNU General Public License as     #
#   published by the Free Software Foundation, either version 3 of     #
#   the License, or any later version.                                 #
#                                                                      #
#   Pax-selector is distributed in the hope that it will be useful,    #
#   but WITHOUT ANY WARRANTY; without even the implied warranty of     #
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the      #
#   GNU General Public License for more details.                       #
#                                                                      #
#   You should have received a copy of the GNU General Public License. #
#   If not, see <http://www.gnu.org/licenses/>.                        #
#                                                                      #
########################################################################
VERSION="0.9.7.1"

#TODOS
# parsing module somewhere else
# fields hashes with symbols, not arrays
# la información de usuarios se guarda en binario, mirar qué hacer con el password


require 'sinatra'
require 'mustache/sinatra'
require 'json'
require 'userInfo'
require 'paxList'
require 'rankingList'



class PaxSelector < Sinatra::Base
  register Mustache::Sinatra
  set :mustache, {
    :views => 'views/',
    :templates => 'templates/'
  }

  use Rack::Session::Pool

  set :public, File.dirname(__FILE__) + '/public'
  set :paxList, PaxList.new

  before do
     session[:messages] = 
      [ {:type => "info", :message => "Welcome to Pax-Selector v.#{VERSION}"} ] if !session[:messages]
    unless request.path == '/login' or 
        request.path == '/message' or 
        request.path == '/logout'
      unless env['warden'].authenticated?
        session[:messages] << {:type => "info", :message => "It seems you need to log in!"} if session[:messages].size < 2
        redirect "/login?redirect=#{request.path}" if request.path != '/'
        redirect "/login"
      end
    end

  end

  get '/login' do
    @redirect = "?redirect=#{params[:redirect]}" if params[:redirect]
    mustache :login
  end

  post '/login' do
    if env['warden'].authenticate(:password)  
      username = env['warden'].user.user
      session[:messages] << {:type => "info", :message => "Welcome #{username}!"}
      redirect (params[:redirect] || '/')
    else 
      session[:messages] << {:type => "error", :message => "Wrong username/password" }
      redirect "/login?redirect=#{params[:redirect]}" if params[:redirect]
      redirect '/login'
    end
  end
  
  get '/logout' do
    env['warden'].logout
    session[:messages] = [ { :type => "info", :message => "Logged out correctly"} ]
    redirect "/login?redirect=#{params[:redirect]}" if params[:redirect]
    redirect "/login"
  end
  
  get '/' do
    @user = env['warden'].user
    @listCount = settings.paxList.size
    @markCount = @user.size
    mustache :home
  end
  
  get '/list' do
    @user = env['warden'].user
    @list = settings.paxList
    mustache :list
  end

  get '/list/:id' do 
    @user = env['warden'].user
    @list = settings.paxList
    @indiv = @list.indiv(params[:id].to_i)
    @mark = @user.mark(params[:id].to_i)
    c = @user.comment(params[:id].to_i)
    @comment = c.force_encoding("ASCII-8BIT") if c
    
    mustache :info
  end 
  
  get '/ranking' do
    @rankingList = RankingList.new
    @list = settings.paxList
    @stats = @rankingList.stats
    
    mustache :ranking
  end
  
  get '/customlist' do
    @list = settings.paxList
    
    mustache :customlist
  end
  
  post '/update' do
    @user = env['warden'].user
    @list = settings.paxList

    id = params[:id].to_i
    name = params[:name]
    mark = params[:rating]
    comment = params[:comment]
    action = params[:action]
 
    if  mark or (comment and comment.size > 0)
      rc = @user.update(id,name,mark,comment,true)
      case (rc)
      when 0
        #nothing
      when 1 
        session[:messages] << {:type => "info", :message => "Information updated"}
      when 2 
        session[:messages] << {:type => "info", :message => "Information updated and saved"}
      else  
        session[:messages] << {:type => "error", :message => "Error updating information"}
      end
    end

    case action
    when "previous"
      if id == 1
        redirect "/list"
      else
        redirect "/list/#{id-1}"
      end
    when "next"
        if id == @list.size
          redirect "/list"
        else
          redirect "/list/#{id+1}"
        end
    when "save"
      redirect "/list/#{id}"
    end
  end
  
  get '/message' do
    messages = session[:messages].to_json
    session[:messages].clear
    return messages
  end
end
